package hiring.tong.com.talent.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;




import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;






import hiring.tong.com.talent.Listener.TalentLoginListener;
import hiring.tong.com.talent.dao.TalentDao;
import hiring.tong.com.talent.entity.TalentEntity;


public class TalentServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private TalentDao talentDao=new TalentDao();
 
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("UTF-8");
		String command=request.getParameter("command");
		if("get".equals(command)){
			get(request,response);
		}
		else if("main".equals(command)){
			main(request,response);
		}
		else if("check".equals(command)){
			check(request,response);
		}
		else if("preUpdate".equals(command)){
			preUpdate(request,response);
		}
		else if("update".equals(command)){
			update(request,response);
		}
		else if("register".equals(command)){
			register(request,response);
		}
		else if("exit".equals(command)){
			exit(request,response);
		}
		else if("fail".equals(command)){
			fail(request,response);
		}
		else if("download".equals(command)){
			download(request,response);
		}
		else{
			throw new RuntimeException("非法操作");
		}
	}
	private void check(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// TODO Auto-generated method stub
		
		String value=request.getParameter("imagevalue");
		
		PrintWriter printWriter=null;
		String kaptcha=(String)request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
		if(!kaptcha.equals(value)){
			try{
				 printWriter = response.getWriter();
				printWriter.print(1);
				
			}
				finally{
					printWriter.close();
				}
			}
		}
		
	

	private void download(HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		// TODO Auto-generated method stub
//		response.setContentType(getServletContext().getMimeType("sound.zip"));
		
		OutputStream output=response.getOutputStream();
		InputStream input=new FileInputStream(new File("D:/sound.mp3"));
		byte[] bytes=new byte[1024];
		int len=0;
		while((len=input.read(bytes))!=-1){
			output.write(bytes, 0, len);
		}
		output.close();
		input.close();
	
		
	}

	private void fail(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	
		String code=request.getParameter("code");
		
		

		request.setAttribute("fialLogin","用户账户和密码不正确，请重新登录");

		request.setAttribute("code", code);
		request.getRequestDispatcher("view/talent/talent-login.jsp").forward(request,response);
		
	}

	private void exit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//关闭会话
		request.getSession().invalidate();
		request.getRequestDispatcher("view/talent/talent-login.jsp").forward(request, response);
	}

	//用户注册
	private void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String code=request.getParameter("code");
		String name=request.getParameter("username");
		String password=request.getParameter("pwd");
		int gender=Integer.parseInt(request.getParameter("gender"));
		int age=Integer.parseInt(request.getParameter("age"));
		String email=request.getParameter("email");
		String phone=request.getParameter("phone");
		StringBuilder sb=new StringBuilder();
		String[] hobbies = request.getParameterValues("interest");
		for(int i=0;i<hobbies.length;i++){
			if(i==hobbies.length-1){
				sb.append(hobbies[i]);
			}else{
			sb.append(hobbies[i]+"|");
			}
		}
		String hobby=sb.toString();
		TalentEntity talent=new TalentEntity();
		talent.setCode(code);
		talent.setAge(age);
		talent.setEmail(email);
		talent.setGender(gender);
		talent.setHobby(hobby);
		talent.setName(name);
		talent.setPassword(password);
		talent.setPhone(phone);
		int row=talentDao.register(talent);
		if(row==1){
			request.getRequestDispatcher("view/talent/talent-login.jsp").forward(request, response);	
		}
		else{
			request.setAttribute("mession","注册失败，请重新注册");
			request.getRequestDispatcher("view/talent/talent-register.jsp").forward(request, response);
		}
		
	}

	private void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		TalentEntity talents=(TalentEntity)request.getSession().getAttribute("talent");
		int id=talents.getId();
		String name=request.getParameter("username");
		String password=request.getParameter("pwd");
		int gender=Integer.parseInt(request.getParameter("gender"));
		int age=Integer.parseInt(request.getParameter("age"));
		String email=request.getParameter("email");
		String phone=request.getParameter("phone");
		StringBuilder sb=new StringBuilder();
		String[] hobbies = request.getParameterValues("interest");
		for(int i=0;i<hobbies.length;i++){
			if(i==hobbies.length-1){
				sb.append(hobbies[i]);
			}
			else{
			sb.append(hobbies[i]+"|");
			}
		}
		String hobby=sb.toString();
		TalentEntity talent=new TalentEntity();
		talent.setId(id);
		talent.setAge(age);
		talent.setEmail(email);
		talent.setGender(gender);
		talent.setHobby(hobby);
		talent.setName(name);
		talent.setPassword(password);
		talent.setPhone(phone);
		int row=talentDao.update(talent);
		if(row==1){
			response.sendRedirect("TalentServlet?command=exit");
				
		}
		else{
			request.setAttribute("mession","修改失败，请重新修改");
			request.getRequestDispatcher("view/talent/talent-update.jsp").forward(request, response);
		}
	}

	private void preUpdate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		TalentEntity talents=(TalentEntity)request.getSession().getAttribute("talent");
		int id=talents.getId();
		TalentEntity talent=talentDao.preUpdate(id);
		request.setAttribute("talent", talent);
		request.getRequestDispatcher("view/talent/talent-update.jsp").forward(request, response);
		
	}

	private void main(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.getRequestDispatcher("view/talent/talent-main.jsp").forward(request, response);
		
	}

	//用户登录
	private void get(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	
		String code=request.getParameter("code");
		String password=request.getParameter("password");
	         System.out.println(code);
		TalentEntity talent=talentDao.get(code,password);
		if("true".equals(request.getParameter("remberinfo"))){
			Cookie[] cook=request.getCookies();
			boolean[] flag={true,true,true}; 
			for(int i=0;i<cook.length;i++){
				if("code".equals(cook[i].getName())){
					if(cook[i].equals(code)){
						flag[0]=false;
					}
				}
				if("password".equals(cook[i].getName())){
					if(cook[i].equals(password)){
						flag[1]=false;
					}
				}
				if("remberinfo".equals(cook[i].getName())){
					if(cook[i].equals(request.getParameter("remberinfo"))){
						flag[2]=false;
					}
				}
				
			}
			if(flag[0]){
			Cookie cookie=new Cookie("code",code);
			cookie.setMaxAge(60 * 30);
			response.addCookie(cookie);
			}
			if(flag[1]){
			Cookie cookies=new Cookie("password",password);
			cookies.setMaxAge(60 * 30);
			response.addCookie(cookies);
			}
			if(flag[2]){
			Cookie cookiess=new Cookie("remberinfo",request.getParameter("remberinfo"));
			cookiess.setMaxAge(60 * 30);
			response.addCookie(cookiess);
			}
		}
		if(talent==null){
		
			request.setAttribute("loginfail","用户账户和密码不正确，请重新登录");
			int count=(Integer)request.getSession().getAttribute("failcount");
			request.setAttribute("code", code);
			response.setCharacterEncoding("UTF-8");
			PrintWriter printWriter=null;
			
			try{
				 printWriter = response.getWriter();
				printWriter.print(count);
				
			}
				finally{
					printWriter.close();
				}
			
		
			return;
		
			
//	     response.sendRedirect("TalentServlet?command=fail&code="+code);
		}
		else{
		
			if("true".equals(request.getParameter("remberinfo"))==false){
				Cookie cookie=new Cookie("code",code);
				Cookie cookies=new Cookie("password",password);
				
				cookie.setMaxAge(60 * 30);
				cookies.setMaxAge(60 * 30);
			
				response.addCookie(cookie);
				response.addCookie(cookies);
			
			}
			TalentLoginListener.failcount=0;
			request.getSession().setAttribute("talent",talent);	
			
			
		}
	}
 
	
	
	
}
